package com.edgardeng.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class JsonUtils {
    public static <T> T readJsonFromClassPath(String path, Type type) throws IOException {

        ClassPathResource resource = new ClassPathResource(path);
        if (resource.exists()) {
            return JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, type,
                    // 自动关闭流
                    Feature.AutoCloseSource,
                    // 允许注释
                    Feature.AllowComment,
                    // 允许单引号
                    Feature.AllowSingleQuotes,
                    // 使用 Big decimal
                    Feature.UseBigDecimal);
        } else {
            throw new IOException();
        }
    }

    public static <T> List<T> readJsonListFromClassPath(String path, Class<T> clazz) throws IOException {

        ClassPathResource resource = new ClassPathResource(path);
        if (resource.exists()) {
            byte[] bytes = new byte[0];
            InputStream is = resource.getInputStream();
            bytes = new byte[is.available()];
            is.read(bytes);
            String str = new String(bytes);
            return JSON.parseArray(str, clazz);
        } else {
            throw new IOException();
        }
    }






//
//    File jsonFile = ResourceUtils.getFile("classpath:tollInfoList.json");
//    String json = FileUtils.readFileToString(jsonFile);
//    JSONArray jsonArray = JSON.parseArray(json);

}
